package com.ytt.start;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ytt.configuration.WebSecurityConfig;
import com.ytt.core.util.SpringUtil;
import com.ytt.core.util.json.ObjectMapperFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * FrameworkAutoConfiguration
 * 自动配置类bean
 * @author chenwen
 * @date 2019/9/12 16:54
 */
@Configuration
@EnableConfigurationProperties({
        SecurityProperties.class
})
@Import({
        WebSecurityConfig.class
})
public class FrameworkAutoConfiguration {


    @Bean
    @Primary
    @ConditionalOnClass({ObjectMapperFactory.class})
    @ConditionalOnProperty({"ytt.core.json.dynamic-filter"})
    @ConditionalOnMissingBean(
            name = {"objectMapper"}
    )
    ObjectMapper objectMapper() {
        return ObjectMapperFactory.getDefaultObjectMapper();
    }


    @Bean
    UserDetailsService userDetailsService(SecurityProperties properties) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = Class.forName("com.ytt.core.api.security.LocalDatabaseUserDetailsServiceImpl");
        UserDetailsService uds = (UserDetailsService) clazz.newInstance();
        SpringUtil.injectBeans(uds);
        return uds;
    }

    @Bean
    PasswordEncoder passwordEncoder(SecurityProperties properties) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = Class.forName("org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder");
        PasswordEncoder pe = (PasswordEncoder) clazz.newInstance();
        SpringUtil.injectBeans(pe);
        return pe;
    }
}
